package com.llmcu.source.mybatisplus.officialsample.quickstart.shiro.controller;

import com.llmcu.source.mybatisplus.officialsample.quickstart.shiro.entity.SysUser;
import com.llmcu.source.mybatisplus.officialsample.quickstart.shiro.mapper.SysUserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * xxxx
 *
 * @author liuling
 * @date 2024/12/12 22:16
 */
@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private SysUserMapper sysUserMapper;
    @GetMapping("hello")
    @ResponseBody
    public String sayHello(){
        List<SysUser> userList = sysUserMapper.selectList(null);
        SysUser user = new SysUser().setName("liuling").setAge(1);
        System.out.println(user);
        userList.forEach(System.out::println);
        return "hello"+userList.size();
    }

    @GetMapping("user-login")
    public String userLogin(String name, String pwd, HttpSession session){
        // 1.获得subject对象
        Subject subject = SecurityUtils.getSubject();
        // 2.封装请求数据到token
        AuthenticationToken token = new UsernamePasswordToken(name,pwd);
        // 3.调用login方法进行登陆认证
        try {
            subject.login(token);
            session.setAttribute("user",token.getPrincipal().toString());
            return "main";
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return "登陆失败";
        }
    }

    @GetMapping("login")
    public String loginResult(){
        return "login";
    }

}
